package cn.itcast.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//网站首页：可以实现显示用户上次访问时间
public class CookieDemo1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		
		PrintWriter out = response.getWriter();
		out.write("这是网站首页！！<br/><br/>");
		
		out.write("您上次访问时间是：");
		//得到上次访问时间
		Cookie cookies[] = request.getCookies();
		for(int i=0;cookies!=null && i<cookies.length;i++){
			Cookie cookie = cookies[i];
			if(cookie.getName().equals("lastAccessTime")){
				Long time = Long.parseLong(cookie.getValue());
				Date d = new Date(time);
				out.write(d.toLocaleString());
			}
		}
		
		
		
		//给用户以cookie的形式送最新的时间
		Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
		cookie.setMaxAge(10000);  //  day06/servlet/
	//	cookie.setPath("/day07");//设置的path需要跟访问的路径一致，否则cookies带不过去
		
		response.addCookie(cookie);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
